package com.rongke.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.ModelPage;
import com.rongke.alipayUtil.alipay.util.AlipayRefundUtil;
import com.rongke.commons.JsonResp;
import com.rongke.enums.*;
import com.rongke.model.*;
import com.rongke.redis.CacheUtil;
import com.rongke.service.*;
import com.rongke.utils.OrderUtils;
import com.rongke.wxPayUtil.wxRefundUtil.wechat.RefundUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @AfterSaleOrderController
 * @售后定订单Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/afterSaleOrder")
@Transactional
@CrossOrigin
public class AfterSaleOrderController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private AfterSaleOrderService afterSaleOrderService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private MuserService muserService;

    @Autowired
    private FlowDetailService flowDetailService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MsgUserService msgUserService;
    @Autowired
    private MessageService messageService;
    /**
     * @添加售后定订单
     * @param afterSaleOrder
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addAfterSaleOrder(@RequestBody AfterSaleOrder afterSaleOrder){
        log.debug("添加售后定订单");
        afterSaleOrderService.insert(afterSaleOrder);
        return JsonResp.ok(afterSaleOrder);
    }


    /**
     * @修改售后定订单
     * @param afterSaleOrder
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateAfterSaleOrder(@RequestBody AfterSaleOrder afterSaleOrder){
        log.debug("修改售后定订单");
        afterSaleOrderService.updateById(afterSaleOrder);
        return JsonResp.ok(afterSaleOrder);
    }
    /**
     * @根据id查找售后定订单
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectAfterSaleOrder(Long id){
        log.debug("查找售后定订单");
        AfterSaleOrder afterSaleOrder = afterSaleOrderService.selectById(id);
        return JsonResp.ok(afterSaleOrder);
    }


    /**
     * @申请售后
     * @param afterSaleOrder
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/applyRefundOrder", method = RequestMethod.POST)
    public JsonResp applyRefundOrder(@RequestBody AfterSaleOrder afterSaleOrder){
        log.debug("申请售后");
        afterSaleOrder.setRefundNumber(OrderUtils.getOrderNo());
        afterSaleOrder.setGmtDatetime(new Date());
        afterSaleOrder.setStatus(1);
        afterSaleOrderService.insert(afterSaleOrder);
        Orders orders=ordersService.selectById(afterSaleOrder.getOrderId());
        BigDecimal orderMoney=orders.getTotalPrice().subtract(orders.getDeliveryMoney());
        if(orderMoney.compareTo(afterSaleOrder.getRefundMoney())!=0){
            afterSaleOrderService.deleteById(afterSaleOrder.getId());
            return JsonResp.fa("退款金额与实际不符");
        }
        orders.setOrderStatus(OrderStatusEnum.ON_REFUND.getType());
        orders.setUptDatetime(new Date());
        ordersService.updateById(orders);
        return JsonResp.ok();
    }


    /**
     * @param modelPage
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectAfterSaleOrders", method = RequestMethod.POST)
    public JsonResp selectAfterSaleOrders(@RequestBody ModelPage<AfterSaleOrder> modelPage){
        log.debug("查找售后定订单");
        Map map=new HashMap();
        AfterSaleOrder afterSaleOrder=modelPage.getT();
        Page page=modelPage.getPage();
        if(afterSaleOrder.getMuserId()!=null){
            map.put("userId",afterSaleOrder.getMuserId());
        }
        if(afterSaleOrder.getStatus()!=null){
            map.put("status",afterSaleOrder.getStatus());
        }
        map.put("startIndex",(page.getCurrent()-1)*page.getSize());
        map.put("size",page.getSize());
        List<AfterSaleOrder> afterSaleOrders = afterSaleOrderService.selectAfterOrders(map);
        Integer total=afterSaleOrderService.selectAfterOrdersSize(map);
        page.setRecords(afterSaleOrders);
        page.setTotal(total);
        return JsonResp.ok(page);
    }


  /*  *//**
     * @根据id查找售后定订单详情
     * @param id 退款订单id
     * @return 返回值JsonResp
     *//*
    @RequestMapping(value="/selectAfterOrderDetail", method = RequestMethod.GET)
    public JsonResp selectAfterOrderDetail(Long id){
        log.debug("查找售后订单详情");
        List<Map> afterSaleOrder=afterSaleOrderService.selectAfterOrderDetail(id);
        List<Map> goods=new ArrayList<>();
        Map aso=new HashMap();
            aso.put("orderNumber",afterSaleOrder.get(0).get("order_number"));
            aso.put("orderId",afterSaleOrder.get(0).get("id"));
            aso.put("leavingMessage",afterSaleOrder.get(0).get("leaving_message"));
            aso.put("gmtDatetime",afterSaleOrder.get(0).get("gmt_datetime"));
            aso.put("payDatetime",afterSaleOrder.get(0).get("pay_datetime"));
            aso.put("uptDatetime",afterSaleOrder.get(0).get("upt_datetime"));
            aso.put("displayName",afterSaleOrder.get(0).get("display_name"));
            aso.put("title",afterSaleOrder.get(0).get("title"));
            aso.put("name",afterSaleOrder.get(0).get("name"));
            aso.put("phone",afterSaleOrder.get(0).get("phone"));
            aso.put("province",afterSaleOrder.get(0).get("province"));
            aso.put("city",afterSaleOrder.get(0).get("city"));
            aso.put("area",afterSaleOrder.get(0).get("area"));
            aso.put("address_detail",afterSaleOrder.get(0).get("address_detail"));
            for (int i=0;i<afterSaleOrder.size();i++) {
              Map goodsMap=new HashMap();
                goodsMap.put("skuCount",afterSaleOrder.get(i).get("sku_count"));
                goodsMap.put("price",afterSaleOrder.get(i).get("price"));
                goodsMap.put("valuesStr",afterSaleOrder.get(i).get("values_str"));
                goodsMap.put("goodsName",afterSaleOrder.get(i).get("goods_name"));
                goods.add(goodsMap);
            }
            aso.put("goodsList",goods);

        return JsonResp.ok(aso);
    }*/

  /** @根据id查找售后定订单详情
     * @param id 退款订单id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectAfterOrderDetail", method = RequestMethod.GET)
    public JsonResp selectAfterOrderDetail(Long id) {
        log.debug("查找售后订单详情");
        AfterSaleOrder afterSaleOrder=afterSaleOrderService.selectById(id);
        return JsonResp.ok(afterSaleOrder);
    }

    /** @会员取消退款
     * @param token 令牌
     *  id  退款id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/cancelRefund", method = RequestMethod.GET)
    public JsonResp cancelRefund(String token,Long id) {
        log.debug("会员取消退款");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa(muserService.LOGINSTR);
        }
        AfterSaleOrder afterSaleOrder=afterSaleOrderService.selectById(id);
        afterSaleOrder.setStatus(2);
        afterSaleOrder.setUptDatetime(new Date());
        afterSaleOrderService.updateById(afterSaleOrder);
        Orders orders=ordersService.selectById(afterSaleOrder.getOrderId());
        orders.setOrderStatus(OrderStatusEnum.PURCHASER_CANCELED.getType());
        orders.setUptDatetime(new Date());
        ordersService.updateById(orders);
        return JsonResp.ok();
    }

    /**
     * @同意或拒绝退款申请
     * @param id 退款id
     *           type 1同意2拒绝
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/agreeRefund", method = RequestMethod.GET)
    public JsonResp agreeRefund(Long id, Integer type){
        log.debug("同意或拒绝退款申请");
        AfterSaleOrder afterSaleOrder=afterSaleOrderService.selectById(id);
        Orders orders=ordersService.selectById(afterSaleOrder.getOrderId());
        String outTradeNo=orders.getOutTradeNo();
        String total_fee=afterSaleOrder.getRefundMoney().toString();
        if(type==1){//同意


            EntityWrapper<Account> ew=new EntityWrapper<>();
            ew.eq("muser_id",orders.getMuserId());
            Account account=accountService.selectOne(ew);
            if(orders.getPayType()== PayTypeEnum.WEIXIN.getType()){
                ClassLoader classLoader=getClass().getClassLoader();
                URL url = classLoader.getResource("apiclient_cert.p12");
                String path=url.getFile();
                String total_feee=new BigDecimal(100).multiply(orders.getCashPayPrice()).setScale(0,BigDecimal.ROUND_HALF_UP).toString();//订单现金实付金额
                String refund_fee=new BigDecimal(100).multiply(afterSaleOrder.getRefundMoney()).setScale(0,BigDecimal.ROUND_HALF_UP).toString();//退款金额
                Map<String, String>  refundMap= RefundUtil.wechatRefund(outTradeNo,total_feee,refund_fee,path);
                    if(refundMap.containsKey("err_code")){
                        return JsonResp.fa(refundMap.get("err_code_des"));
                    }else if("FAIL".equals(refundMap.get("return_code"))){
                        return JsonResp.fa(refundMap.get("return_msg"));
                    } else {
                        afterSaleOrder.setOutRefundNo(String.valueOf(refundMap.get("out_refund_no")));
                        account.setTotalMoney(account.getTotalMoney().subtract(orders.getTotalPrice()));
                        account.setUnavailableDuobi(account.getUnavailableDuobi().subtract(orders.getReturnDuobi()));
                        account.setUnavailableYabi(account.getUnavailableYabi().subtract(orders.getReturnYabi()));
                    }
                /******************退款记录*************************/
                FlowDetail fd=new FlowDetail();
                fd.setMuserId(orders.getMuserId());
                fd.setMoney(new BigDecimal(total_fee));
                fd.setFlowType(FlowTypeEnum.FEFUNDYWX.getType());
                fd.setTitle("微信退款"+total_fee);
                fd.setGmtDatetime(new Date());
                flowDetailService.insert(fd);

            }else if(orders.getPayType()== PayTypeEnum.ZHIFUBAO.getType()){
              String strResponse=  AlipayRefundUtil.alipayRefundRequest(outTradeNo,"",Double.valueOf(total_fee));
                if(strResponse!=null){
                    return JsonResp.fa(strResponse);
                }
                account.setTotalMoney(account.getTotalMoney().subtract(orders.getTotalPrice()));
                account.setUnavailableDuobi(account.getUnavailableDuobi().subtract(orders.getReturnDuobi()));
                account.setUnavailableYabi(account.getUnavailableYabi().subtract(orders.getReturnYabi()));
                /******************退款记录*************************/
                FlowDetail fd=new FlowDetail();
                fd.setMuserId(orders.getMuserId());
                fd.setMoney(new BigDecimal(total_fee));
                fd.setFlowType(FlowTypeEnum.FEFUNDYZFB.getType());
                fd.setTitle("支付宝退款"+total_fee);
                fd.setGmtDatetime(new Date());
                flowDetailService.insert(fd);

            }else{
                if(orders.getPayType()== PayTypeEnum.DUOBI.getType()) {
                    account.setDuoBi(account.getDuoBi().add(new BigDecimal(total_fee)));
                    account.setTotalMoney(account.getTotalMoney().subtract(orders.getTotalPrice()));
                    account.setUnavailableDuobi(account.getUnavailableDuobi().subtract(orders.getReturnDuobi()));
                    account.setUnavailableYabi(account.getUnavailableYabi().subtract(orders.getReturnYabi()));
                }else if(orders.getPayType()== PayTypeEnum.YABI.getType()){
                    account.setYaBi(account.getYaBi().add(new BigDecimal(total_fee)));
                }
                /******************退款记录*************************/
                FlowDetail fd=new FlowDetail();
                fd.setMuserId(orders.getMuserId());
                fd.setMoney(new BigDecimal(total_fee));
                if(orders.getPayType()== PayTypeEnum.DUOBI.getType()) {
                    fd.setFlowType(FlowTypeEnum.FEFUNDDUOBI.getType());
                    fd.setTitle("哆币退款"+total_fee);
                }else if(orders.getPayType()== PayTypeEnum.YABI.getType()){
                    fd.setFlowType(FlowTypeEnum.FEFUNDYABI.getType());
                    fd.setTitle("雅币退款"+total_fee);
                }
                fd.setGmtDatetime(new Date());
                flowDetailService.insert(fd);
            }
            afterSaleOrder.setStatus(4);
            afterSaleOrder.setUptDatetime(new Date());
            //更新订单状态
            orders.setOrderStatus(OrderStatusEnum.REFUNDED.getType());
            ordersService.updateById(orders);
            //更新账户余额
            accountService.updateById(account);
            //*******推荐人不可用余额减掉*******//
            Muser recomendMuser = muserService.findFirstRecomendUser(orders.getMuserId(), UserTypeEnum.CENTURION.getType());
            if (recomendMuser != null) {
                JSONObject jsonRecomend = accountService.updateRecomendUserAccount(recomendMuser.getId(), orders.getId());
                if ("500".equals(jsonRecomend.getString("code"))) {
                    return JsonResp.fa(jsonRecomend.getString("message"));
                }
            }
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为千夫长，则第一个千夫长不可用余额增加
            Muser chiefCommander = muserService.findFirstRecomendUser(orders.getMuserId(), UserTypeEnum.ChIEFCOMMANDER.getType());
            if (chiefCommander != null) {
                JSONObject jsonChief = accountService.updateRecomendUserAccount(chiefCommander.getId(), orders.getId());
                if ("500".equals(jsonChief.getString("code"))) {
                    return JsonResp.fa(jsonChief.getString("message"));
                }
            }
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为加盟商，则第一个加盟商不可用余额增加
            Muser franchisee = muserService.findFirstRecomendUser(orders.getMuserId(), UserTypeEnum.FRANCHISEE.getType());
            if (franchisee != null) {
                JSONObject jsonChief = accountService.updateRecomendUserAccount(franchisee.getId(), orders.getId());
                if ("500".equals(jsonChief.getString("code"))) {
                    return JsonResp.fa(jsonChief.getString("message"));
                }
            }

            /******* 退款成功提示消息******/
            Message msg=messageService.selectTemplateMsgByMsgType(2);
            if(null!=msg){
                String title=msg.getTitle();
                String totalFee=total_fee.toString();
                String content=msg.getContent()
                        .replace("#orderNumber#",orders.getOrderNumber())
                        .replace("#totalFee#",totalFee);
                MsgUser msgUser=new MsgUser();
                msgUser.setMuserId(orders.getMuserId());
                msgUser.setTitle(title);
                //"你刚刚收到来自订单号为 #orderNumber# 的退款，退款金额为：#totalFee#"
                msgUser.setMsgContent(content);
                msgUserService.insert(msgUser);
            }
            /******* 退款成功提示消息******/

    }else if(type==2){
            afterSaleOrder.setStatus(3);
            afterSaleOrder.setUptDatetime(new Date());
        }
        afterSaleOrderService.updateById(afterSaleOrder);


        return JsonResp.ok();
    }











}
